package com.yb.xczx.cloud.auth.config;

import com.yb.core.web.db.annotation.EnableXczxResource;
import com.yb.core.model.WhiteListProperties;
import com.yb.xczx.cloud.auth.filter.XczxUserAuthenticationFilter;
import com.yb.xczx.cloud.auth.filter.XczxUserLoginCodeAuthenticationFilter;
import com.yb.xczx.cloud.auth.filter.XczxUserPassAuthenticationFilter;
import com.yb.xczx.cloud.auth.handler.LoginSuccessHandler;
import com.yb.xczx.cloud.auth.handler.XczxAccessDeniedHandler;
import com.yb.xczx.cloud.auth.handler.XczxAuthenticationEntryPoint;
import com.yb.xczx.cloud.auth.provider.XczxUserLoginCodeAuthenticationProvider;
import com.yb.xczx.cloud.auth.provider.XczxUserPassAuthenticationProvider;
import com.yb.xczx.cloud.auth.service.ISysUserService;
import com.yb.xczx.cloud.auth.service.impl.SysUserServiceImpl;
import com.yb.xczx.security.resource.config.CustomAuthoritiesOpaqueTokenIntrospector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.CollectionUtils;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/13 17:52
 * FileName: SecurityConfig
 * Description:
 */

@Configuration
@Slf4j
@EnableXczxResource
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class HttpSecurityConfig implements ApplicationContextAware {

    private ApplicationContext applicationContext;
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public ISysUserService sysUserService() {
        return new SysUserServiceImpl();
    }



    @Bean
    protected AuthenticationManager configure(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        ProviderManager manager = (ProviderManager) authenticationConfiguration.getAuthenticationManager();
        manager.getProviders().add(xczxUserLoginCodeAuthenticationProvider());
        manager.getProviders().add(xczxUserPassAuthenticationProvider());
        return manager;
    }
    @Autowired
    AuthenticationManager authenticationManager;

    @Bean
    XczxUserPassAuthenticationFilter xczxUserPassAuthenticationFilter(){
        XczxUserPassAuthenticationFilter authenticationFilter = new XczxUserPassAuthenticationFilter(authenticationManager);
        return authenticationFilter;
    }

    @Bean
    XczxUserLoginCodeAuthenticationFilter xczxUserLoginCodeAuthenticationFilter(){
        return new XczxUserLoginCodeAuthenticationFilter(authenticationManager);
    }
    @Bean
    XczxUserAuthenticationFilter xczxUserAuthenticationFilter(){
        return new XczxUserAuthenticationFilter();
    }

    @Bean
    XczxUserPassAuthenticationProvider xczxUserPassAuthenticationProvider(){
        return new XczxUserPassAuthenticationProvider() ;
    }

    @Bean
    XczxUserLoginCodeAuthenticationProvider xczxUserLoginCodeAuthenticationProvider(){
        return new XczxUserLoginCodeAuthenticationProvider();
    }

    @Bean
    AccessDeniedHandler accessDeniedHandler(){
        return new XczxAccessDeniedHandler();
    }

    @Bean
    AuthenticationEntryPoint authenticationEntryPoint(){
        return new XczxAuthenticationEntryPoint();
    }

    @Bean
    LoginSuccessHandler loginSuccessHandler(){
        return new LoginSuccessHandler();
    }

    @Autowired
    WhiteListProperties whiteListProperties;

    @Value("${spring.application.name}")
    String appName;
    @Bean
    @Order(3)
    public SecurityFilterChain httpSecurityFilterChain(HttpSecurity http) throws Exception {
        // @formatter:off
        log.info("secure application {} whiteList:{}",appName,whiteListProperties.getUrls());
        http
                .authorizeHttpRequests((authorize) -> {
                    if (!CollectionUtils.isEmpty(whiteListProperties.getUrls())) {
                        authorize.antMatchers(whiteListProperties.getUrls().toArray(new String[whiteListProperties.getUrls().size()])).permitAll();
                    }
                    authorize.anyRequest().authenticated();
                });
        http.csrf().disable();
        http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .successHandler(loginSuccessHandler())
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(xczxUserPassAuthenticationProvider())
                .authenticationProvider(xczxUserLoginCodeAuthenticationProvider())
                .addFilterBefore(xczxUserAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)

                .addFilterBefore(xczxUserPassAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)

                .addFilterBefore(xczxUserLoginCodeAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);

        http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);

        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint());
            ;
        // @formatter:on
        return http.build();
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }


    @Bean
    OpaqueTokenIntrospector opaqueTokenIntrospector(){
        return new CustomAuthoritiesOpaqueTokenIntrospector();
    }

}
